package com.bbg.amyam.web.mvc.infrastructure;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.bbg.amyam.domain.enumtype.ActiveStatusCode;
import com.bbg.amyam.domain.model.Profile;
import com.bbg.amyam.domain.model.School;

@Component
@DependsOn(value = {"entityManagerFactory", "transactionManager", "dataSource"})
@Lazy(value = false)
public class DataInitializer implements InitializingBean {

	 @PersistenceContext
	    private EntityManager entityManager;
	 
	 @Autowired
	    private PlatformTransactionManager transactionManager;
	 
	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		setupData();
	}

	private void setupData() {
		TransactionStatus status = transactionManager.getTransaction(
                new DefaultTransactionDefinition());
		Profile profile=setupDefaultAdminProfile();
		setupDefaultSchool(profile);
		 transactionManager.commit(status);
	}

	private Profile setupDefaultAdminProfile() {
		List<Profile> profileList = Profile.findProfilesByEmailEquals("admin@amyam.com").getResultList();
		if(profileList.size()>0){
			return profileList.get(0);
		}else{
			Profile profile=new Profile();
			profile.setEmail("admin@amyam.com");
			profile.setLastName("System");
			profile.setFirstName("Admin");
			profile.persist();
			return profile;
		}
	}
	private void setupDefaultSchool(Profile profile) {

		List<School> schoolList = School.findSchoolsByShortNameEquals("default").getResultList();
		if(schoolList.size()<1){
			School school=new School();
			school.setShortName("default");
			school.setFullName("Amyam default school");
			school.setActiveStatus(ActiveStatusCode.Inactive);
			school.setAdminProfile(profile);
			school.setLogoURL("/resources/images/amyam.JPG");
			school.persist();
		}
		
	}

}
